package org.example.uhy.repository.config;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.example.uhy.supports.utils.LocalDateTimeUtils;

import java.sql.*;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {
    ZoneId zoneId;

    public LocalDateTimeTypeHandler(ZoneId zoneId) {
        this.zoneId = zoneId;
    }

    public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, parameter);
    }

    public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return toLocalDateTime(rs.getObject(columnName));
    }

    public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return toLocalDateTime(rs.getObject(columnIndex));
    }

    public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return toLocalDateTime(cs.getObject(columnIndex));
    }

    private LocalDateTime toLocalDateTime(Object ts) throws SQLFeatureNotSupportedException {
        if (ts == null) {
            return null;
        }
        if (ts instanceof LocalDateTime) {
            return (LocalDateTime) ts;
        } else if (ts instanceof Timestamp) {
            return ((Timestamp) ts).toLocalDateTime();
        } else if (ts instanceof Date) {
            return ((Date) ts).toInstant().atZone(zoneId).toLocalDateTime();
        } else if (ts instanceof String) {
            return LocalDateTimeUtils.parse((String) ts);
        } else {
            throw new SQLFeatureNotSupportedException();
        }
    }
}